package com.hqd.ch03.test.scope;

import com.hqd.ch03.v10.config.Scope;
import com.hqd.ch03.v10.factory.ObjectFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程作用域
 */
public class ThreadScope implements Scope {
    private final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal() {
        @Override
        protected Object initialValue() {
            return new HashMap<>();
        }
    };

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Map scope = threadLocal.get();
        Object obj = scope.get(name);
        if (obj == null) {
            obj = objectFactory.getObject();
            scope.put(name, obj);
        }
        return obj;
    }

    @Override
    public Object remove(String name) {
        return threadLocal.get().remove(name);
    }

}
